<template>
  <el-dialog :visible="showdialog"
             width="100%"
             :before-close="closeBtn"
             title="写文章"
             :append-to-body="true">
    <el-form :model="artFrom"
             :rules="rules"
             ref="artFrom"
             label-width="100px"
             class="demo-ruleForm">
      <el-form-item label="文章标题"
                    prop="title">
        <el-input v-model="artFrom.title"></el-input>
      </el-form-item>
      <el-form-item label="文章分类"
                    prop="region">
        <el-select v-model="artFrom.cate_id"
                   placeholder="请选择分类"
                   size="small"
                   style="width:100%"
                   @focus="getArtCate">
          <el-option v-for="item in cates"
                     :key="item.id"
                     :label="item.cate_name"
                     :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="文章内容"
                    prop="content">
        <quill-editor v-model="artFrom.content"
                      ref="myQuillEditor"
                      :options="editorOption"
                      @blur="onEditorBlur($event)"
                      @focus="onEditorFocus($event)"
                      @change="onEditorChange($event)">
        </quill-editor>
      </el-form-item>
      <el-form-item label="文章封面"
                    prop="name">
        <el-button type="primary"
                   @click="submitForm('userInfo')"
                   style="background:#fff;border:#DCDCDC solid 1px;color:#000;margin-bottom:15px">选择头像</el-button>
        <br>
        <img ref="study"
             :src="studyDataPic">
        <input type="file"
               multiple
               id="eve"
               style="display:none"
               @change="add" />
        <br>
      </el-form-item>
    </el-form>
    <div slot="footer"
         style="float:left;margin-left:100px;padding-bottom:10px">
      <el-button type="primary"
                 @click="onSubmit(false)">发布</el-button>
      <el-button @click="onSubmit(true)">存为草稿</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { quillEditor } from 'vue-quill-editor'

import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

// import { ref } from 'vue'

import { getArtCate, addArt } from '@/api/article'
// const imgSrc = ref('')
export default {
  name: 'ArtPubPage',
  props: {
    showdialog: {
      type: Boolean,
      default: false
    }
  },
  components: {
    quillEditor
  },
  data () {
    return {
      cates: [],
      artFrom: {
        title: '',
        cate_id: '',
        content: '',
        cover_img: '',
        state: ''
      },
      content: '<p></p><p><br></p><ol><li><strong><em>Or drag/paste an image here.</em></strong></li><li><strong><em>rerew</em></strong></li><li><strong><em>rtrete</em></strong></li><li><strong><em>tytrytr</em></strong></li><li><strong><em>uytu</em></strong></li></ol>',
      str: '',
      editorOption: {
        placeholder: '这里可以填写内容',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            ['blockquote', 'code-block'], // 引用，代码块
            [{ header: 1 }, { header: 2 }], // 标题，键值对的形式；1、2表示字体大小
            [{ list: 'ordered' }, { list: 'bullet' }], // 列表
            [{ script: 'sub' }, { script: 'super' }], // 上下标
            [{ indent: '-1' }, { indent: '+1' }], // 缩进
            [{ direction: 'rtl' }], // 文本方向
            [{ size: ['small', false, 'large', 'huge'] }], // 字体大小
            [{ header: [1, 2, 3, 4, 5, 6, false] }], // 几级标题
            [{ color: [] }, { background: [] }], // 字体颜色，字体背景颜色
            [{ font: [] }], // 字体
            [{ align: [] }], // 对齐方式
            ['clean'], // 清除字体样式
            ['image', 'video'] // 上传图片、上传视频
          ]
        }
      },
      studyDataPic: require('@/assets/images/cover.jpg'),
      rules: {
        title: [{ required: true, message: '题目不能为空', trigger: 'blur' }, { min: '1', max: '30', message: '题目字符应为1-30字符', trigger: 'blur' }],
        content: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
        cate_id: [{ required: true, message: '分类不能为空', trigger: 'blur' }],
        cover_img: [{ required: true, message: '封面不能为空', trigger: 'blur' }]

      }
    }
  },
  methods: {
    onEditorReady (editor) { }, // 准备编辑器
    onEditorBlur () { }, // 失去焦点事件
    onEditorFocus () { }, // 获得焦点事件
    onEditorChange () { }, // 内容改变事件
    // 转码
    escapeStringHTML (str) {
      str = str.replace(/&lt;/g, '<')
      str = str.replace(/&gt;/g, '>')
      return str
    },
    async getArtCate () {
      const res = await getArtCate()
      // console.log(res.data.data)
      this.cates = res.data.data
    },
    // 发布按钮
    onSubmit (bool) {
      this.$refs.artFrom.validate(async valid => {
        if (bool) {
          // 存为草稿
          console.log('草稿')
          this.artFrom.state = '草稿'
          console.log('this.artFrom:', this.artFrom)
          const res = await addArt(this.artFrom)
          console.log('res:', res)
        } else {
          // 发布
          console.log('发布')
          this.artFrom.state = '已发布'
          console.log('this.artFrom:', this.artFrom)
          const res = await addArt(this.artFrom)
          console.log('res:', res)
        }
      })
      // this.$router.push('/art_list')
      this.$emit('getArtList')
      this.$emit('update:showdialog', false)
    },
    async add (e) {
      // console.log('e', e)
      // console.log('e.target.files', e.target.files)

      const file = e.target.files[0]
      if (file.type !== 'image/jpeg' && file.type !== 'image/bmp' && file.type !== 'image/png') {
        this.$message.error('请上传JPEG、JPG、BMP、PNG格式文件')
        e.target.value = ''
        return
      }

      const reader = new FileReader()
      // console.log('reader', reader)

      reader.readAsDataURL(file)
      reader.onload = e => {
        // console.log('e----', e)
        // console.log('e.target.result', e.target.result)
        this.studyDataPic = e.target.result
        this.artFrom.cover_img = file
      }

      // if (file.size > 3 * 1024 * 1024) {
      //   this.$message.error('请上传大小在3M以内的图片')
      //   e.target.value = ''
      //   return
      // }
    },
    closeBtn () {
      this.artFrom = {
        title: '',
        cate_id: '',
        content: '',
        cover_img: '',
        state: ''
      }
      this.$refs.artFrom.resetFields()
      this.$emit('update:showdialog', false)
    },
    submitForm () {
      document.getElementById('eve').click()
    }
  },
  computed: {
    editor () {
      return this.$refs.myQuillEditor.quill
    }
  },
  mounted () {
    const content = '' // 请求后台返回的内容字符串
    this.str = this.escapeStringHTML(content)
  }
}
</script>

<style>
.el-dialog {
  position: absolute;
  top: -100px;
}
.ql-editor {
  height: 300px;
}
</style>
